package com.study.juc.interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @program: juc-study
 * @author: Zhoujian
 * @date: 2022-08-13 14:59
 * @version: 1.0
 * @description: 如何停止中断运行中的线程
 *      通过 volatile 实现线程中断
 *      通过 AtomicBoolean 实现线程中断
 *      通过 Thread 类中提供的 api 实现
 *
 **/
public class InterruptDemo {
	private static volatile boolean isStop = false;
//	private static boolean isStop = false;
	static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

	public static void main(String[] args) {
		// 通过 Thread 类中提供的 api 实现线程中断
		Thread t1 = new Thread(() -> {
			while (true) {
				if (Thread.currentThread().isInterrupted()) {
					System.out.println(Thread.currentThread().getName() + "线程------isInterrupted = true,自己退出了");
					break;
				}
				System.out.println("-------hello isInterrupted api");
			}
		}, "t1");

		t1.start();

		//暂停几秒钟线程
		try {
			TimeUnit.MILLISECONDS.sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(() -> {
			t1.interrupt();
		}).start();
	}

	/**
	 * 通过 atomicBoolean 实现线程中断
	 */
	private static void m2() {
		new Thread(() -> {
			while (true) {
				if (atomicBoolean.get()) {
					System.out.println(Thread.currentThread().getName() + "线程------atomicBoolean = true,自己退出了");
					break;
				}
				System.out.println("-------hello atomicBoolean");
			}
		}, "t1").start();

		//暂停几秒钟线程
		try {
			TimeUnit.MILLISECONDS.sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(() -> {
			atomicBoolean.set(true);
		}).start();
	}

	/**
	 * 通过 volatile 实现线程中断
	 */
	private static void m1() {
		new Thread(() -> {
			while (true) {
				if (isStop) {
					System.out.println(Thread.currentThread().getName() + "线程------isStop = true,自己退出了");
					break;
				}
				System.out.println("-------hello interrupt");
			}
		}, "t1").start();

		//暂停几秒钟线程
		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		new Thread(() -> {
			isStop = true;
		}).start();
	}
}
